package middle;

import java.util.HashMap;
import java.util.Map;

/**
 * 给定两个整数数组 inorder 和 postorder ，其中 inorder 是二叉树的中序遍历， 
 * postorder 是同一棵树的后序遍历，请你构造并返回这颗二叉树。
 *
 * 链接：https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal
 * @author 胡宇轩
 * @Email: programboy@163.com
 */
public class ConstructBinaryTreeFromInorderAndPostorderTraversal {
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.buildTree(new int[] {-4,-10,3,-1,7,11,-8,2}, new int[] {-4,-1,3,-10,11,-8,2,7});
    }
    static class Solution {
        Map<Integer, Integer> map = new HashMap<>();
        int[] post;
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            for (int i = 0; i < inorder.length; i++) {
                map.put(inorder[i], i);
            }
            post = postorder;
            return recur(0, inorder.length-1, 0, inorder.length-1);
        }

        private TreeNode recur(int is, int ie, int ps, int pe) {
            if (is > ie || ps > pe) {
                return null;
            }
            int curNodeValue = post[pe];
            Integer index = map.get(curNodeValue);
            TreeNode curNode = new TreeNode(curNodeValue);
            curNode.left = recur(is, index-1, ps, pe - (ie-index) - 1);
            curNode.right = recur(index + 1, ie, pe - (ie-index), pe - 1);
            return curNode;
        }
    }
}